package view;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.AbstractMap.SimpleEntry;
import java.util.LinkedHashMap;
import qw.easyFrame.tools.statics.StringUtil;

/**
 * 将文本显示在窗口.
 * @author Rex
 *
 */
public class PrintOnFrame {

	/**
	 * 文本域.
	 */
	private EasyTextPane area;
	
	/**
	 * 是否打印统计次数;
	 */
	private boolean counted;
	
	/**
	 * 待打印的信息.
	 */
	private List<SimpleEntry<String, Integer>> find;
	
	public PrintOnFrame() {
		super();
	}

	public void setArea(EasyTextPane area) {
		this.area = area;
	}

	public void setCounted(boolean counted) {
		this.counted = counted;
	}

	public void setFind(List<SimpleEntry<String, Integer>> find) {
		this.find = find;
	}

	/**
	 * 打印文本.
	 * @param find
	 */
	public void print() {
		if (counted) {
			printCounted();
		} else {
			literallyPrint();
		}
	}
	
	/**
	 * 打印文本出现次数.
	 */
	private void printCounted() {
		Map<String, Integer> map = new LinkedHashMap<>();

		for (SimpleEntry<String, Integer> e : find) {
			String fname = e.getKey();
			int value = e.getValue();

			if (value == -1) {// 错误信息不需要统计，直接加入map
				map.put(fname, value);
			} else {
				Integer count;
				if ((count = map.get(fname)) == null) {// 首次出现的文件，加入map并计数1次
					map.put(fname, 1);
				} else {// 重复出现的文件，统计值+1
					map.put(fname, ++count);
				}
			}
		}
		
		for (Entry<String, Integer> e : map.entrySet()) {
			String fname = e.getKey();
			int value = e.getValue();
			
			StringBuilder sb = new StringBuilder(fname);
			if (value != -1) {
				sb.append(" 出现").append(value).append("次");
				area.append(sb.toString());
			} else {
				area.appendErrMsg(sb.toString());
			}
		}

	}
	
	/**
	 * 按“页”计数的文档格式.
	 */
	private static final String[] PAGED = new String[] { ".xls", ".xlsx", ".pdf", ".ppt", "pptx" };

	/**
	 * 直接打印信息.
	 */
	private void literallyPrint() {
		for (SimpleEntry<String, Integer> e : find) {
			String fname = e.getKey();
			int value = e.getValue();
			
			StringBuilder sb = new StringBuilder(fname);
			if (value != -1) {
				sb.append(" 第").append(value);
				if (StringUtil.endsWith(fname, PAGED))
					sb.append("页");
				else
					sb.append("段");
				
				area.append(sb.toString());
			} else {
				area.appendErrMsg(sb.toString());
			}
		}
	}
	
}